# -*- coding: utf-8 -*-
"""
    Time    : 2020/12/27 9:46 下午
    Author  : Thinkgamer
    File    : 072-编辑距离.py
    Desc    : https://leetcode-cn.com/problems/edit-distance/
"""

"""
给你两个单词word1和word2，请你计算出将word1转换成word2 所使用的最少操作数。

你可以对一个单词进行如下三种操作：
- 插入一个字符
- 删除一个字符
- 替换一个字符

示例1：
输入：word1 = "horse", word2 = "ros"
输出：3
解释：
horse -> rorse (将 'h' 替换为 'r')
rorse -> rose (删除 'r')
rose -> ros (删除 'e')

示例2：
输入：word1 = "intention", word2 = "execution"
输出：5
解释：
intention -> inention (删除 't')
inention -> enention (将 'i' 替换为 'e')
enention -> exention (将 'n' 替换为 'x')
exention -> exection (将 'n' 替换为 'c')
exection -> execution (插入 'u')

提示：

0 <= word1.length, word2.length <= 500
word1 和 word2 由小写英文字母组成
"""

"""
	2019年腾讯阅文面试时问过这道题，当时没写出来
	思路：动态规划
"""


# 164 ms 77.08% | 18.2 MB 13.57%
def min_distance(word1: str, word2: str) -> int:
	m = len(word1) + 1
	n = len(word2) + 1
	# dp 表示 word1 第 i 位 变成 word2 第 j 位 需要的最小操作数
	dp = [[0] * n for _ in range(m)]
	for i in range(m):
		dp[i][0] = i
	for j in range(n):
		dp[0][j] = j
	
	for i in range(1, m):
		for j in range(1, n):
			if word1[i-1] == word2[j-1]:
				dp[i][j] = dp[i-1][j-1]
			else:
				dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1
	return dp[m-1][n-1]


for word1, word2 in [
	["horse", "ros"],
	["intention", "execution"],
	["", ""],
	["", "a"],
	["a", "a"]
]:
	result = min_distance(word1, word2)
	print(result)
